package contact.servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import contact.domain.Address;
import contact.domain.Contact;
import contact.domain.DAOContact;
import contact.domain.DAOPhoneNumber;
import contact.domain.PhoneNumber;


public class UpdateContact extends HttpServlet {
	private static final long serialVersionUID = 1840411036952534195L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		DAOContact daoContact = (DAOContact) context.getBean("DAOContact");
		DAOPhoneNumber daoPhone = (DAOPhoneNumber) context.getBean("DAOPhoneNumber");
		try{
			Long id = new Long (request.getParameter("id"));
			String firstname = request.getParameter("firstname");
			String lastname = request.getParameter("lastname");
			String email = request.getParameter("email");
			String street = request.getParameter("street");
			String city = request.getParameter("city");
			String zip = request.getParameter("zip");
			String country = request.getParameter("country");
			String mobile = request.getParameter("mobile");
			String home = request.getParameter("home");
			String job = request.getParameter("job");
			
			Contact contact = daoContact.read(id);
			contact.setFirstName(firstname);
			contact.setLastName(lastname);
			contact.setEmail(email);
			
			Address address = contact.getAddress();
			address.setStreet(street);
			address.setCity(city);
			address.setZip(zip);
			address.setCountry(country);
			
			contact.setAddress(address);
			
			daoContact.update(contact);
			
			for (PhoneNumber phone : contact.getProfiles()){
				if (phone.getPhoneKind().compareTo(PhoneNumber.MOBILE) == 0){
					phone.setPhoneNumber(mobile);
					daoPhone.update(phone);
				}
				else if (phone.getPhoneKind().compareTo(PhoneNumber.HOME) == 0){
					phone.setPhoneNumber(home);
					daoPhone.update(phone);
				}
				else if (phone.getPhoneKind().compareTo(PhoneNumber.JOB) == 0){
					phone.setPhoneNumber(job);
					daoPhone.update(phone);
				}
			}

			RequestDispatcher rd = request.getRequestDispatcher("/accueil.jsp");
			rd.forward(request, response);
		}
		catch(NumberFormatException e){    }
		
		/*RequestDispatcher rd = request.getRequestDispatcher("/accueil.jsp");
		rd.forward(request, response);*/
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

}
